import React, {useEffect, useState} from 'react';
import ProForm, {ProFormText, ProFormTextArea, ProFormDigit} from '@ant-design/pro-form';
import {Modal, message, Cascader, Form, Input, Upload, Button, Avatar, Image, Tree} from 'antd';
import { getAdminMenuList, getAdminRoleInfo, editAdminRole, addAdminRole } from '@/services/rule';
import styles from './index.less';

import {getRegionList} from "@/services/setting";

const Edit = (props) => {
  const {isModalVisible, isShowModal, actionRef, editId} = props;

  const [expandedKeys, setExpandedKeys] = useState([]); // 展开的节点
  const [checkedKeys, setCheckedKeys] = useState([]); // 选中的节点
  const [checkedKeysData, setCheckedKeysData] = useState([]); // 选中的节点，传递给后端的数据
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [menuList, setMenuList] = useState([]); // 菜单数据


  const [formLayout] = useState('horizontal');

  const title = editId === null ? '添加用户' : '编辑用户';

  const formItemLayout =
    formLayout === 'horizontal' ? {labelCol: {span: 4}, wrapperCol: {span: 20}} : null;

  useEffect(() => {
    // getMenuList()
  }, [])

  // const getMenuList = () => {
  //
  //   // getAdminMenuList().then((res) => {
  //   //   setMenuList(res.data.list);
  //   // })
  //
  //   if (!localStorage.getItem('treeMenuData')) {
  //     getAdminMenuList().then((res) => {
  //       setMenuList(res.data.list);
  //       localStorage.setItem('treeMenuData', JSON.stringify(res.data.list));
  //     })
  //   } else {
  //     setMenuList(JSON.parse(localStorage.getItem('treeMenuData')));
  //   }
  // }

  const getMenuList = (admin_menu_ids = []) => {

    getAdminMenuList().then((res) => {
      setMenuList(res.data.list)
      setExpandedKeys(admin_menu_ids)
      setCheckedKeys(admin_menu_ids)
    })

  }

  /**
   * 获取数据
   * 作者：糜家智
   * 时间：2021/8/2 18:03
   */
  const getData = async () => {
    const res = await getAdminRoleInfo({
      admin_role_id: editId,
    });
    getMenuList(res.data.admin_menu_ids)
    return res.data;
  };

  /**
   * 作者：糜家智
   * 时间：2022/04/18 17:32:00
   * 功能：提交按钮
   */
  const handleSubmit = async (values) => {
    const data = values;
    data.admin_menu_ids = checkedKeysData.join(',')

    let res = {};

    if (editId === null) {
      res = await addAdminRole(data);
    } else {
      data.admin_role_id = editId;
      res = await editAdminRole(data);
    }

    if (res.code === 200) {
      message.success(res.msg);
      actionRef.current.reload();
      isShowModal(false);
    }
  };

  /**
   * 作者：糜家智
   * 时间：2022/04/27 15:43:45
   * 功能：展开事件
   */
  const onExpand = (expandedKeysValue) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  /**
   * 作者：糜家智
   * 时间：2022/04/27 15:45:58
   * 功能：点击复选框触发事件
   */
  const onCheck = (checkedKeysValue, info) => {
    // console.log(checkedKeysValue)
    // let checkedKey = checkedKeysValue.concat(info.halfCheckedKeys);
    // console.log(checkedKey)
    setCheckedKeysData(checkedKeysValue.concat(info.halfCheckedKeys))
    setCheckedKeys(checkedKeysValue);
  };

  return (
    <Modal
      title={title}
      visible={isModalVisible}
      onCancel={() => isShowModal(false)}
      footer={null}
      destroyOnClose={true}
    >
      <ProForm
        onFinish={(values) => handleSubmit(values)}
        request={
          editId == null
            ? () => {
              getMenuList()
              return {sort: 50};
            }
            : () => getData()
        }
        {...formItemLayout}
        layout={formLayout}
      >
        <ProFormText
          name="role_name"
          label="名称"
          placeholder="请输入名称"
          rules={[{required: true, message: '名称不能为空'}]}
        />
        <ProFormTextArea name="role_desc" label="描述" placeholder="请输入描述"/>
        <Form.Item
          name="role_sort"
          label="排序"
          rules={[
            {
              message: '请输入正确的数字',
              pattern: /^[0-9]*$/,
            },
          ]}
        >
          <Input placeholder="排序"/>
        </Form.Item>
        <Form.Item label="菜单">
          <Tree
            checkable
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            treeData={menuList}
            // multiple={true}
            // checkStrictly={true}
            fieldNames={{title: 'menu_name', key: 'admin_menu_id'}}
          />
        </Form.Item>
      </ProForm>
    </Modal>
  );
};

export default Edit;
